<template>
  <div id="app">
    <MYHEADER></MYHEADER>
    <div id="bodyApp">
      <!-- {{isAllFull}} -->
      <MYITEM
        v-for="item in dataList"
        :key="item.id"
        :id="item.id"
        :title="item.goods_name"
        :pic="item.goods_img"
        :price="item.goods_price"
        :state="item.goods_state"
        :count="item.goods_count"
        @changeChecked="getChecked"
      >
        <BUT :count="item.goods_count" @editCount="getNum(item, $event)"></BUT>
      </MYITEM>
    </div>

    <FOOTER
      :total_goods="total_goods"
      :total_price="total_price"
      @allChecked="allChecked"
      :isAllChecked="isAllFull"
    ></FOOTER>
  </div>
</template>

<script>
// import bus from "@/bus.js";
import axios from "axios";
import MYHEADER from "@/components/myHeader.vue";
import MYITEM from "@/components/myItem.vue";
import FOOTER from "@/components/footer.vue";
import BUT from "@/components/but.vue";
export default {
  data() {
    return {
      dataList: [],
      isFull: {
        status: false,
      },
    };
  },
  methods: {
    async getListData() {
      const { data: res } = await axios.get("http://localhost:8000/getGoods");
      this.dataList = res.list;
    },
    getChecked(co) {
      // 得到子组件选中的状态和id

      this.dataList.some((item) => {
        if (item.id === co.id) item.goods_state = co.checked;
      });
    },
    allChecked(val) {
      // console.log(val);
      this.dataList.forEach((item) => {
        item.goods_state = val;
      });
    },
    getNum(item, e) {
      // e为自定义事件，里面只有一个数值
      item.goods_count = e
    },
  },
  created() {
    this.getListData();
    this.getChecked();
  },
  computed: {
    isAllFull() {
      // 是否全部被选中
      return this.dataList.every((item) => item.goods_state);
    },
    // 计算总价钱和商品数目
    total_price() {
      return this.dataList
        .filter((item) => item.goods_state)
        .reduce((total, item) => {
          return total + item.goods_count * item.goods_price;
        }, 0);
    },
    total_goods() {
      return this.dataList
        .filter((item) => item.goods_state)
        .reduce((total, item) => {
          return total + item.goods_count;
        }, 0);
    },
  },
  components: {
    MYHEADER,
    MYITEM,
    FOOTER,
    BUT,
  },
};
</script>

<style scoped lang="less">
* {
  margin: 0 auto;
  padding: 0;
}
#bodyApp {
  margin: 40px 0;
}
</style>